﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Data;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using bus_TienichNPC;
using BaocaoNPC.common;
using CMISLibrary;
using CMISLibrary.Libraries;
using BaocaoNPC.Usercontrols.reports;

namespace BaocaoNPC.Usercontrols
{
    /// <summary>
    /// Interaction logic for GIAO_HDON.xaml
    /// </summary>
    public partial class GIAO_HDON : UserControl
    {
        #region variable
        public String strMadviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public string strUsername = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap : "NPC_ATM";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        public String strTen_dviqly_CT = NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT : "cap tren";
        DataSet dsResult = new DataSet();
        DataSet ds_ketqua = new BCNPCEntities.EXCEL.ds_CN();
        DataSet ds_TNV = new DataSet();
        DataSet data_report = new DataSet();
        NPC_CHAMNO_OFFLINE_bus CHAMNO_OFFLINE_Bus = new NPC_CHAMNO_OFFLINE_bus();
        #endregion

        public GIAO_HDON()
        {
            InitializeComponent();
            try
            {
                ds_TNV = GlobalServices.Service_NPCUS.TNV_CHITIET_HDON(strMadviqly);
                Load_Tv(ds_TNV);
                Update_autotext();
            }
            catch (Exception ex)
            { }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private void Update_autotext()
        {
            try
            {
                if (ds_TNV.Tables.Count == 0)
                {
                    txtGiaTri.ClearItem();
                    return;
                }
                DataTable dt = new DataTable();
                DataColumn Col1 = dt.Columns.Add("MA_TNGAN", typeof(String));
                dt.Columns.Add("TEN_TNGAN", typeof(String));
                var result = (from row in ds_TNV.Tables[0].AsEnumerable()
                              group row by new { MA_TNGAN = row.Field<string>("MA_TNGAN"), TEN_TNGAN = row.Field<string>("TEN_TNGAN") } into grp
                              orderby grp.Key.MA_TNGAN
                              select new
                              {
                                  MA_TNGAN = grp.Key.MA_TNGAN,
                                  TEN_TNGAN = grp.Key.TEN_TNGAN,
                              }).ToList();
                for (int i = 0; i < result.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["MA_TNGAN"] = result[i].MA_TNGAN;
                    dr["TEN_TNGAN"] = result[i].TEN_TNGAN;
                    dt.Rows.Add(dr);
                    dt.AcceptChanges();
                }
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                ds.AcceptChanges();
                ProcessData(ds);
                txtGiaTri.ClearItem();
                if (ds != null) txtGiaTri.AddItem(new CMIS2_TextBox.AutoCompleteEntry(ds.Tables[0], "DataTable"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void ProcessData(DataSet ds)
        {
            try
            {
                foreach (DataTable dt in ds.Tables)
                {
                    if (dt.Columns.Count > 0)
                    {
                        dt.Columns.AddRange(new DataColumn[] { new DataColumn("SEARCH", typeof(string)), new DataColumn("MA_SEARCH", typeof(string)), new DataColumn("TEN_SEARCHED", typeof(string)) });
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr["SEARCH"] = dr["MA_TNGAN"].ToString() + "-" + dr["TEN_TNGAN"].ToString();
                            dr["MA_SEARCH"] = dr["SEARCH"];
                            dr["TEN_SEARCHED"] = dr["TEN_TNGAN"];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                string ma_tngan = strUsername.ToUpper();
                CheckBox chk = (CheckBox)sender;
                this.Cursor = Cursors.Wait;
                TreeViewItem itemselect = tvTNV.SelectedItem as TreeViewItem;
                string[] m = chk.Tag.ToString().Split('@');
                if (chk.IsChecked == true)
                {
                    foreach (TreeViewItem supernode in tvTNV.Items)
                    {
                        checkList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in tvTNV.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }

                    // nếu click nút cha                        
                    if (m[1].ToString() == "NUTCHA")
                    {
                        #region NUTCHA
                        //lấy dữ liệu của nút cha                               
                        dsResult = GlobalServices.Service_NPCUS.ChamnoOff_Nutcha(ma_tngan, strMadviqly);

                        if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
                        {
                            if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0)
                            {
                                copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[0]);
                                ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                            }
                            else
                            {
                                for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                                {
                                    if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                                    {
                                        ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                                    }
                                }
                                ds_ketqua.AcceptChanges();
                                copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[0]);
                                ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                            }
                            dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                        }
                        #endregion
                    }

                    else if (m[3].ToString() == "NUTCHA2")
                    {
                        #region NUTCHA2
                        try
                        {
                            // lấy dữ liệu của nút cha2   
                            dsResult = GlobalServices.Service_NPCUS.ChamnoOff_Nutcha2(Convert.ToInt32(m[0]), ma_tngan, strMadviqly);

                            if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
                            {
                                if (dsResult.Tables[0].Rows.Count > 0)
                                {
                                    if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0)
                                    {
                                        copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[1]);
                                        ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                                    }
                                    else
                                    {
                                        for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                                        {
                                            if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["SO_BBGIAO"].ToString() == m[0].ToString())
                                            {
                                                ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                                            }
                                        }
                                        ds_ketqua.AcceptChanges();
                                        copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[1]);
                                        ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                                    }
                                }
                            }
                            dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        #endregion
                    }
                    else if (m[4].ToString() == "NUTCON")
                    {
                        #region NUTCON
                        try
                        {
                            // lấy dữ liệu của nút con   
                            dsResult = GlobalServices.Service_NPCUS.ChamnoOff_Nutcon(m[0], Convert.ToInt32(m[1]), ma_tngan, strMadviqly);

                            if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
                            {
                                if (dsResult.Tables[0].Rows.Count > 0)
                                {
                                    if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0)
                                    {
                                        copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[2]);
                                        ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                                    }
                                    else
                                    {
                                        for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                                        {
                                            if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["MA_SOGCS"].ToString() == m[0].ToString())
                                            {
                                                ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                                            }
                                        }
                                        ds_ketqua.AcceptChanges();
                                        copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[2]);
                                        ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                                    }
                                }
                            }
                            dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                        }
                        catch (Exception ex)
                        { }
                        #endregion
                    }
                }
                else
                {
                    #region Uncheck
                    foreach (TreeViewItem supernode in tvTNV.Items)
                    {
                        UncheckList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in tvTNV.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    if (m[0] == "NUTGOC")
                    {
                        ds_ketqua.Tables["GIAO_HDON"].Rows.Clear();
                        dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                    }
                    // nếu click nút cha
                    if (m[1].ToString() == "NUTCHA")
                    {
                        #region Uncheck NUTCHA
                        if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0) return;
                        for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                        {
                            if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                            {
                                ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                            }
                        } //end of for loop     

                        ds_ketqua.AcceptChanges();
                        ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                        dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                        #endregion
                    }
                    if (m[3].ToString() == "NUTCHA2")
                    {
                        #region Uncheck NUTCHA2
                        if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0) return;
                        for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                        {
                            if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["SO_BBGIAO"].ToString() == m[0].ToString())
                            {
                                ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                            }
                        } //end of for loop     

                        ds_ketqua.AcceptChanges();
                        ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                        dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                        #endregion
                    }
                    if (m[4].ToString() == "NUTCON")
                    {
                        #region Uncheck NUTCON
                        if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0) return;
                        for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                        {
                            if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["MA_SOGCS"].ToString() == m[0].ToString())
                            {
                                ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                            }
                        } //end of for loop     

                        ds_ketqua.AcceptChanges();
                        ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                        dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                        #endregion
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Arrow;
                MessageBox.Show(ex.Message.ToString());
                return;
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }

        }

        private void checkList(TreeViewItem nodes, CheckBox chk)
        {
            if ((CheckBox)nodes.Header == chk)
            {
                CheckAllChildsWhenParentCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    if (node.Items.Count > 0)
                    {

                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = true;
                            if (subNode.Items.Count > 0)
                            {
                                checkList(subNode, chkNode);
                            }
                        }
                        CheckParentWhenAllChildChecked(nodes);
                    }
                    else
                    {
                        CheckParentWhenAllChildChecked(nodes);
                    }
                }
                else
                {
                    checkList(node, chk);
                }

            }
            //dt.AcceptChanges();
        }

        private void UncheckList(TreeViewItem nodes, CheckBox chk)
        {
            //dt.Rows.Clear();
            if ((CheckBox)nodes.Header == chk)
            {
                UnCheckAllChildsWhenParentUnCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    UnCheckParent(node);
                    if (node.Items.Count > 0)
                    {
                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = false;
                            if (subNode.Items.Count > 0)
                            {
                                UncheckList(subNode, chkNode);
                            }
                            //load database of childnode
                            //KiemTra_Insert_tbl_All_TheoDoiNo(chkChildNode);
                        }
                    }
                    else
                    {
                        CheckBox chkNode = (CheckBox)node.Header;
                        chkNode.IsChecked = false;
                    }
                }
                else
                {
                    UncheckList(node, chk);
                }
            }
        }

        private void UnCheckParent(TreeViewItem node)
        {
            TreeViewItem parentNode = node.Parent as TreeViewItem;
            if (parentNode != null)
            {
                CheckBox chkParentNode = (CheckBox)parentNode.Header;
                chkParentNode.IsChecked = false;
                UnCheckParent(parentNode);
            }
        }

        private void RefreshCheckBoxList(TreeViewItem nodes)
        {
            DataRow[] dr = null;
            foreach (TreeViewItem subNode in nodes.Items)
            {
                //check all Node
                CheckBox chkNode = (CheckBox)subNode.Header;
                if (subNode.Items.Count > 0)
                {
                    RefreshCheckBoxList(subNode);
                }
                else
                {
                    if (chkNode.IsChecked == true)
                    {

                    }
                    else
                    {

                    }
                }
            }
        }

        private void CheckAllChildsWhenParentCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = true;
                CheckAllChildsWhenParentCheck(node);
            }
        }

        private void UnCheckAllChildsWhenParentUnCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = false;
                UnCheckAllChildsWhenParentUnCheck(node);
            }
        }

        private void CheckParentWhenAllChildChecked(TreeViewItem nodes)
        {
            int count = 0;
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                if (chkNode.IsChecked == false)
                {
                    count = count + 1;
                    break;
                }
            }
            if (count == 0)
            {
                CheckBox chkNode = (CheckBox)nodes.Header;
                chkNode.IsChecked = true;
                TreeViewItem parentNode = nodes.Parent as TreeViewItem;
                if (parentNode != null)
                {

                    CheckParentWhenAllChildChecked(parentNode);
                }
            }
        }

        private void Load_Tv(DataSet ds)
        {
            try
            {
                if (ds.Tables[0].Rows.Count == 0) return;
                TreeViewItem superNode = new TreeViewItem();
                TreeViewItem _node = new TreeViewItem();
                TreeViewItem _childnode = new TreeViewItem();
                CheckBox chkNode = new CheckBox();
                CheckBox chkChildNode = new CheckBox();
                CheckBox chkSuperNode = new CheckBox();

                this.tvTNV.Items.Clear(); // xoa tree trước khi đỗ dữ liệu mới
                DataView dv = new DataView(ds.Tables[0]);
                dv.Sort = "MA_TNGAN";
                if (dv.Count == 0) // không có dữ liệu không đưa ra tree
                {
                    superNode.Header = "Không có dữ liệu TNV";
                    superNode.Tag = "Không có dữ liệu TNV@";
                    tvTNV.Items.Add(superNode);
                    return;
                }
                chkSuperNode = new CheckBox();
                chkSuperNode.Content = strTen_dviqly;
                chkSuperNode.Tag = "NUTGOC" + "@" + "" + "@" + "" + "@" + "" + "@" + "";
                chkSuperNode.ToolTip = strTen_dviqly;
                chkSuperNode.IsChecked = false;
                chkSuperNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                superNode = new TreeViewItem();
                superNode.Header = chkSuperNode;
                superNode.IsExpanded = true;
                //superNode.IsSelected = true;
                tvTNV.Items.Add(superNode);
                string strnutcha = "";
                string strNutCon = "";
                string str_thungan = "";
                string str_ma_thungan = "";
                foreach (DataRowView dr in dv)
                {
                    str_ma_thungan = dr["MA_TNGAN"].ToString();
                    str_thungan = dr["TEN_TNGAN"].ToString();

                    #region "parentnode"
                    if (str_thungan != strnutcha)
                    {
                        chkNode = new CheckBox();
                        chkNode.Content = str_thungan;// +" -" + dr["NGAY_GIAO"].ToString();
                        chkNode.Tag = str_ma_thungan + "@NUTCHA" + "@" + "" + "@" + "" + "@" + "";
                        chkNode.ToolTip = str_thungan;
                        chkNode.IsChecked = false;
                        chkNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                        _node = new TreeViewItem();
                        _node.Header = chkNode;
                        _node.IsExpanded = false;
                        superNode.Items.Add(_node);
                        strnutcha = str_thungan;

                        //So BBG
                        #region SoBBG
                        DataSet dsBBG = new DataSet();
                        dsBBG = GlobalServices.Service_NPCUS.ChamnoOff_Nutcha(str_ma_thungan.ToUpper(),strMadviqly);
                        if (dsBBG != null && dsBBG.Tables[0].Rows.Count > 0)
                        {
                            if (dsBBG.Tables.Count > 0 && dsBBG.Tables[0].Rows.Count > 0)
                            {
                                TreeViewItem superNodeBB = new TreeViewItem();
                                TreeViewItem _nodeBB = new TreeViewItem();
                                //TreeViewItem _childnodeBB = new TreeViewItem();
                                //CheckBox chkNodeBB = new CheckBox();
                                CheckBox chkChildNodeBB = new CheckBox();

                                // filter_treeDataSet();
                                //this._node.Items.Clear(); // xoa tree trước khi đỗ dữ liệu mới
                                DataView dv2 = new DataView(dsBBG.Tables[0]);
                                dv2.Sort = "SO_BBGIAO, MA_SOGCS";
                                string strnutcha2 = "";
                                string str_bienban2 = "";
                                string str_ma_sogcs = "";
                                foreach (DataRowView dr2 in dv2)
                                {
                                    str_bienban2 = dr2["SO_BBGIAO"].ToString();
                                    str_ma_sogcs = dr2["MA_SOGCS"].ToString();
                                    #region "parentnode2"
                                    if (str_bienban2 != strnutcha2)
                                    {
                                        CheckBox chkNodeBB = new CheckBox();
                                        chkNodeBB.Content = str_bienban2;
                                        chkNodeBB.Tag = str_bienban2 + "@" + str_ma_thungan + "@" + "Biên bản" + "@NUTCHA2" + "@" + "";
                                        chkNodeBB.ToolTip = str_bienban2;
                                        chkNodeBB.IsChecked = false;
                                        chkNodeBB.Click += new RoutedEventHandler(this.CheckBox_Click);
                                        _nodeBB = new TreeViewItem();
                                        _nodeBB.Header = chkNodeBB;
                                        _nodeBB.IsExpanded = false;
                                        _node.Items.Add(_nodeBB);
                                        strnutcha2 = str_bienban2;


                                    }
                                    # endregion
                                    #region Ma So GCS

                                    TreeViewItem _nodeSo = new TreeViewItem();
                                    CheckBox chkChildNodeSo = new CheckBox();
                                    if (str_ma_sogcs != strNutCon)
                                    {
                                        CheckBox chkNodeSo = new CheckBox();
                                        chkNodeSo.Content = str_ma_sogcs;
                                        chkNodeSo.Tag = str_ma_sogcs + "@" + str_bienban2 + "@" + str_ma_thungan + "@" + "Sổ" + "@NUTCON";
                                        chkNodeSo.ToolTip = str_ma_sogcs;
                                        chkNodeSo.IsChecked = false;
                                        chkNodeSo.Click += new RoutedEventHandler(this.CheckBox_Click);
                                        _nodeSo = new TreeViewItem();
                                        _nodeSo.Header = chkNodeSo;
                                        _nodeSo.IsExpanded = false;
                                        _nodeBB.Items.Add(_nodeSo);
                                        strNutCon = str_ma_sogcs;
                                    }
                                    #endregion

                                }
                            }
                        }

                        #endregion
                    }
                    # endregion

                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        private void copy_dataTable(DataTable dtnguon, DataTable dtDich, string ma_tngan)
        {
            try
            {
                DataRow[] rgINS = dtnguon.Select();
                for (int i = 0; i < rgINS.Length; i++)
                {
                    DataRow dr = dtDich.NewRow();
                    if (rgINS[i]["TIEN_NOP"].ToString() == "0")
                        dr["CHECK"] = "X";
                    dr["MA_KHANG"] = rgINS[i]["MA_KHANG"];
                    dr["ID_HDON"] = rgINS[i]["ID_HDON"];
                    dr["TIEN"] = rgINS[i]["Tien"];
                    dr["MA_SOGCS"] = rgINS[i]["MA_SOGCS"];
                    dr["SO_BBGIAO"] = rgINS[i]["SO_BBGIAO"];
                    dr["MA_KVUC"] = rgINS[i]["MA_KVUC"];
                    dr["TEN_DCHI"] = rgINS[i]["TEN_DCHI"];
                    dr["KY"] = rgINS[i]["KY"];
                    dr["THANG"] = rgINS[i]["THANG"];
                    dr["NAM"] = rgINS[i]["NAM"];
                    dr["DV"] = rgINS[i]["HTHUC_TTOAN"];
                    dr["MA_TNGAN"] = rgINS[i]["MA_TNGAN"];
                    dr["TEN_TNGAN"] = rgINS[i]["TEN_TNGAN"];
                    dr["SERY"] = rgINS[i]["SO_SERY"];
                    dr["NGAY_GIAO"] = rgINS[i]["NGAY_GIAO"];
                    dtDich.Rows.Add(dr);
                    dtDich.AcceptChanges();
                }
            }
            catch (Exception ex)
            { }
        }

        private void btnIn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BaocaoNPC.Usercontrols.reports.RP_CHITIET_GIAOHDON report = new BaocaoNPC.Usercontrols.reports.RP_CHITIET_GIAOHDON();
                report.SetDataSource(ds_ketqua.Tables["GIAO_HDON"]);
                report.SetParameterValue("CONGTY", strTen_dviqly);
                report.SetParameterValue("CONGTYCAPTREN", strTen_dviqly_CT);
                report.SetParameterValue("NGAYIN", GlobalServices.Service_NPCUS.Datetime());
                UtilReportOMS.RptManager.showReportToWin(this, report, strMadviqly, new string[] { "Formula1", "Formula2", "Formula3" }, new string[] { "Formula1", "Formula2", "Formula3" }, "CMIS2 - Report: Báo cáo NPC");
            }
            catch (Exception ex)
            { return; }
        }

        private void btnTimkiem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtGiaTri.Text == "") return;
                tvTNV.Items.Clear();
                ds_ketqua.Tables["GIAO_HDON"].Rows.Clear();
                dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                string[] tngan = txtGiaTri.Text.Split('-');
                TreeViewItem superNode = new TreeViewItem();
                TreeViewItem _node = new TreeViewItem();
                TreeViewItem _childnode = new TreeViewItem();
                CheckBox chkNode = new CheckBox();
                CheckBox chkChildNode = new CheckBox();
                CheckBox chkSuperNode = new CheckBox();

                this.tvTNV.Items.Clear();
                chkSuperNode = new CheckBox();
                chkSuperNode.Content = strTen_dviqly;
                chkSuperNode.Tag = "NUTGOC" + "@" + "" + "@" + "" + "@" + "" + "@" + "";
                chkSuperNode.ToolTip = strTen_dviqly;
                chkSuperNode.IsChecked = false;
                chkSuperNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                superNode = new TreeViewItem();
                superNode.Header = chkSuperNode;
                superNode.IsExpanded = true;
                tvTNV.Items.Add(superNode);
                string strNutCon = "";
                string str_thungan = "";
                string str_ma_thungan = "";

                str_ma_thungan = tngan[0];
                str_thungan = tngan[1];

                #region "parentnode"
                chkNode = new CheckBox();
                chkNode.Content = tngan[1];
                chkNode.Tag = tngan[0] + "@NUTCHA" + "@" + "" + "@" + "" + "@" + "";
                chkNode.ToolTip = tngan[1];
                chkNode.IsChecked = false;
                chkNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                _node = new TreeViewItem();
                _node.Header = chkNode;
                _node.IsExpanded = false;
                superNode.Items.Add(_node);

                //So BBG
                #region SoBBG
                DataSet dsBBG = new DataSet();
                dsBBG = GlobalServices.Service_NPCUS.ChamnoOff_Nutcha(tngan[0].ToUpper(), strMadviqly);
                if (dsBBG != null && dsBBG.Tables[0].Rows.Count > 0)
                {
                    if (dsBBG.Tables.Count > 0 && dsBBG.Tables[0].Rows.Count > 0)
                    {
                        TreeViewItem superNodeBB = new TreeViewItem();
                        TreeViewItem _nodeBB = new TreeViewItem();
                        //TreeViewItem _childnodeBB = new TreeViewItem();
                        //CheckBox chkNodeBB = new CheckBox();
                        CheckBox chkChildNodeBB = new CheckBox();

                        // filter_treeDataSet();
                        //this._node.Items.Clear(); // xoa tree trước khi đỗ dữ liệu mới
                        DataView dv2 = new DataView(dsBBG.Tables[0]);
                        dv2.Sort = "SO_BBGIAO, MA_SOGCS";
                        string strnutcha2 = "";
                        string str_bienban2 = "";
                        string str_ma_sogcs = "";
                        foreach (DataRowView dr2 in dv2)
                        {
                            str_bienban2 = dr2["SO_BBGIAO"].ToString();
                            str_ma_sogcs = dr2["MA_SOGCS"].ToString();
                            //str_ma_sogcs = dr2["MA_SOGCS"].ToString();

                            #region "parentnode2"
                            if (str_bienban2 != strnutcha2)
                            {
                                CheckBox chkNodeBB = new CheckBox();
                                chkNodeBB.Content = str_bienban2;
                                chkNodeBB.Tag = str_bienban2 + "@" + str_ma_thungan + "@" + "Biên bản" + "@NUTCHA2" + "@" + "";
                                chkNodeBB.ToolTip = str_bienban2;
                                chkNodeBB.IsChecked = false;
                                chkNodeBB.Click += new RoutedEventHandler(this.CheckBox_Click);
                                _nodeBB = new TreeViewItem();
                                _nodeBB.Header = chkNodeBB;
                                _nodeBB.IsExpanded = false;
                                _node.Items.Add(_nodeBB);
                                strnutcha2 = str_bienban2;


                            }
                            # endregion
                            #region Ma So GCS

                            TreeViewItem _nodeSo = new TreeViewItem();
                            CheckBox chkChildNodeSo = new CheckBox();
                            if (str_ma_sogcs != strNutCon)
                            {
                                CheckBox chkNodeSo = new CheckBox();
                                chkNodeSo.Content = str_ma_sogcs;
                                chkNodeSo.Tag = str_ma_sogcs + "@" + str_bienban2 + "@" + str_ma_thungan + "@" + "Sổ" + "@NUTCON";
                                chkNodeSo.ToolTip = str_ma_sogcs;
                                chkNodeSo.IsChecked = false;
                                chkNodeSo.Click += new RoutedEventHandler(this.CheckBox_Click);
                                _nodeSo = new TreeViewItem();
                                _nodeSo.Header = chkNodeSo;
                                _nodeSo.IsExpanded = false;
                                _nodeBB.Items.Add(_nodeSo);
                                strNutCon = str_ma_sogcs;
                            }
                            #endregion

                        }
                    }
                }
                #endregion
                # endregion
            }
            catch (Exception ex)
            {
                return;
            }            
        }

        private void txtGiaTri_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    if (txtGiaTri.Text.Trim() == "")
                    {
                        MessageBox.Show("Không có giá trị tìm kiếm!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    else
                    {
                        string[] m = txtGiaTri.Text.Split('-');
                        ds_TNV.Tables[0].DefaultView.RowFilter = "TEN_TNGAN = '" + m[1].ToUpper() + "'";
                        if (ds_TNV.Tables[0].DefaultView.Count == 0)
                        {
                            MessageBox.Show("Mã sổ không có giá trị tìm kiếm!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        Find(tvTNV, m[1].ToUpper());
                        txtGiaTri.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        private void Find(TreeView mainTreeView, string findToText)
        {
            //ds_Ketqua.Tables["CN"].Rows.Clear();
            foreach (object item in mainTreeView.Items)
            {
                TreeViewItem treeItem = mainTreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

                if (treeItem != null)
                {
                    FindAll(treeItem, findToText);
                }
                if (item != null)
                {
                    //treeItem.IsExpanded = true;
                    CheckBox chkNode = (CheckBox)treeItem.Header;
                    string[] m = chkNode.Tag.ToString().Split('@');
                    // string obje = treeItem.Header.ToString();
                    if (isContains(chkNode.Content.ToString(), findToText))
                    {
                        chkNode.IsChecked = true;
                        #region NUTCHA
                        // lấy dữ liệu của nút cha                               
                        dsResult = GlobalServices.Service_NPCUS.ChamnoOff_Nutcha(m[0], strMadviqly);

                        if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
                        {
                            if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0)
                            {
                                copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[0]);
                                ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                            }
                            else
                            {
                                for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                                {
                                    if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                                    {
                                        ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                                    }
                                }
                                ds_ketqua.AcceptChanges();
                                copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[0]);
                                ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                            }
                        }
                        #endregion
                    }
                }
            }
        }

        private void FindAll(ItemsControl items, string findToText)
        {
            foreach (object obj in items.Items)
            {
                ItemsControl childControl = items.ItemContainerGenerator.ContainerFromItem(obj) as ItemsControl;
                if (childControl != null)
                {
                    FindAll(childControl, findToText);
                }
                TreeViewItem item = childControl as TreeViewItem;

                if (item != null)
                {
                    CheckBox chkNode = (CheckBox)item.Header;
                    string[] m = chkNode.Tag.ToString().Split('@');
                    if (isContains(chkNode.Content.ToString(), findToText))
                    {
                        chkNode.IsChecked = true;
                        #region NUTCHA
                        // lấy dữ liệu của nút cha      
                        
                        dsResult = GlobalServices.Service_NPCUS.ChamnoOff_Nutcha(m[0], strMadviqly);

                        if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
                        {
                            if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0)
                            {
                                copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[0]);
                                ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                            }
                            else
                            {
                                for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                                {
                                    if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                                    {
                                        ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                                    }
                                }
                                ds_ketqua.AcceptChanges();
                                copy_dataTable(dsResult.Tables[0], ds_ketqua.Tables["GIAO_HDON"], m[0]);
                                ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                            }
                            dgrHdon.ItemsSource = ds_ketqua.Tables["GIAO_HDON"].DefaultView;
                        }
                        #endregion
                    }
                }
            }
        }

        private bool isContains(string a, string b)
        {
            if (a.ToUpper().Trim() == b.ToUpper().Trim())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void CHECK_HOADON_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                this.Cursor = Cursors.Wait;
                DataRowView drv = dgrHdon.SelectedItem as DataRowView;
                string id = drv.Row["ID_HDON"].ToString();
                if (chk.IsChecked == true)
                {
                    #region Check
                    DataRow dr = ds_ketqua.Tables["GIAO_HDON"].NewRow();
                    dr["MA_KHANG"] = drv.Row["MA_KHANG"];
                    dr["ID_HDON"] = drv.Row["ID_HDON"];
                    dr["CHECK"] = drv.Row["CHECK"];
                    dr["TIEN"] = drv.Row["TTIEN"];
                    dr["MA_SOGCS"] = drv.Row["MA_SOGCS"];
                    dr["SO_BBGIAO"] = drv.Row["SO_BBGIAO"];
                    dr["MA_KVUC"] = drv.Row["MA_KVUC"];
                    dr["TEN_DCHI"] = drv.Row["TEN_DCHI"];
                    dr["KY"] = drv.Row["KY"];
                    dr["THANG"] = drv.Row["THANG"];
                    dr["NAM"] = drv.Row["NAM"];
                    dr["DV"] = drv.Row["HTHUC_TTOAN"];
                    dr["NGAY_GIAO"] = drv.Row["NGAY_GIAO"];
                    dr["MA_TNGAN"] = drv.Row["MA_TNGAN"];
                    ds_ketqua.Tables["GIAO_HDON"].Rows.Add(dr);
                    ds_ketqua.AcceptChanges();
                    ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                    #endregion
                }
                else
                {
                    if (ds_ketqua.Tables["GIAO_HDON"].Rows.Count == 0) return;
                    for (int i = ds_ketqua.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                    {
                        if (ds_ketqua.Tables["GIAO_HDON"].Rows[i]["ID_HDON"].ToString() == id)
                        {
                            ds_ketqua.Tables["GIAO_HDON"].Rows[i].Delete();
                        }
                    }
                    ds_ketqua.AcceptChanges();
                    ds_ketqua.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                }
            }
            catch (Exception ex)
            { }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }
    }
}
